package com.binvshe.binvshe.app.home;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.binvshe.binvshe.R;
import com.binvshe.binvshe.account.ParamKey;
import com.binvshe.binvshe.account.utils.StringFormatUtil;
import com.binvshe.binvshe.common.http.DataRequestListener;
import com.binvshe.binvshe.common.http.ListDataRequestListener;
import com.binvshe.binvshe.common.http.MyHttpRequest;
import com.binvshe.binvshe.common.http.MyResponseParser;
import com.binvshe.binvshe.common.http.UrlCenter;
import com.binvshe.binvshe.common.image.IML;
import com.binvshe.binvshe.mine.usercenter.UserCenterActivity;
import com.binvshe.binvshe.mine.view.CommentDialog;
import com.f2prateek.dart.Dart;
import com.f2prateek.dart.InjectExtra;
import com.pachong.android.baseuicomponent.adapter.RecyclerViewBaseAdapter;
import com.pachong.android.baseuicomponent.fragment.SwipeListFragment;
import com.pachong.android.framework.httprequest.UrlParams;
import com.pachong.android.frameworkbase.utils.EasyToast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by Administrator on 2016/9/18.
 */
public class CommentFragment extends SwipeListFragment {

    private static final String KEY_TARGET_ID = "key_target_id";
    private static final String KEY_TYPE = "TYPE";

    @InjectExtra(KEY_TARGET_ID)
    int mTargetId;
    @InjectExtra(KEY_TYPE)
    String mType;

    public static CommentFragment newInstance(int targetId,String type) {
        Bundle args = new Bundle();
        args.putInt(KEY_TARGET_ID, targetId);
        args.putString(KEY_TYPE,type);
        CommentFragment fragment = new CommentFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        Dart.inject(this, getArguments());
        EventBus.getDefault().register(this);
        startLoading();
        return view;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public RecyclerViewBaseAdapter createAdapter() {
        return new CommentListAdapter(getActivity());
    }

    @Override
    public void onStartLoading() {
        getDataList();
    }

    @Override
    public void onStartRefreshing() {
        super.onStartRefreshing();
        getData().clear();
        mlastid = 0;
        startLoading();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventRefresh(ClassEvent.RefreshEvent refreshEvent) {
        onStartRefreshing();
    }

    private final static int PAGE_SIZE = 10;
    private int lastListSize = 0;
    int mlastid = 0;

    MyResponseParser<CommentEntity> parser = new MyResponseParser<CommentEntity>(CommentEntity.class) {

        @Override
        public boolean hasMore() {
            if (lastListSize >= PAGE_SIZE) {
                return true;
            } else {
                return false;
            }
        }
    };

    ListDataRequestListener mResponceListener = new ListDataRequestListener(this, parser) {
        @Override
        public void onSuccess(Object listData) {
            super.onSuccess(listData);
            if (getData().size() > 0) {
                mlastid = ((CommentEntity) getData().get(getData().size() - 1)).getId();
            }
            List<CommentEntity> list = (List<CommentEntity>) listData;
            if (list != null) {
                lastListSize = list.size();
            }
        }
    };

    public void getDataList() {
        MyHttpRequest request = new MyHttpRequest(getContext());
        UrlParams urlParams = new UrlParams();
        String url = String.format(UrlCenter.COMMENT_LIST, mType, mTargetId);
        urlParams.put("size", PAGE_SIZE + "");
        urlParams.put("last_id", mlastid + "");
        request.get(url, urlParams, mResponceListener);
    }

    public class CommentListAdapter extends RecyclerViewBaseAdapter<CommentEntity> {


        public CommentListAdapter(Context con) {
            super(con);
        }

        @Override
        public RecyclerView.ViewHolder onCreateHolder(ViewGroup parent, int viewType) {
            return new VH(setAdapterViewItem(parent, R.layout.item_comment_list));
        }

        @Override
        public void onBindHolder(RecyclerView.ViewHolder holder, final int position) {
            final VH viewHolder = (VH) holder;
            final CommentEntity commentItem = getData().get(position);
            final CommentEntity.UserBean user = commentItem.getUser();
            if (!TextUtils.isEmpty(user.getNick_name()))
                viewHolder.mTvName.setText(user.getNick_name());
            if (!TextUtils.isEmpty(user.getPortrait()))
                IML.load(getContext(), viewHolder.mCirHead, user.getPortrait());

            if (user.getClub() != null) {
                if (!TextUtils.isEmpty(user.getClub().getName())) {
                    viewHolder.mTvClubName.setText(user.getClub().getName());
                } else {
                    viewHolder.mTvClubName.setText("");
                }
            }else {
                viewHolder.mTvClubName.setText("");
            }
            //设置评论内容
            if (!TextUtils.isEmpty(commentItem.getContent())) {
                if (commentItem.getReply_user() == null) {
                    viewHolder.mTvComment.setText(commentItem.getContent());
                } else {
                    String AllContent = "回复 @" + commentItem.getReply_user().getNick_name() + " : " + commentItem.getContent();
                    //设置被评论者昵称颜色高亮
                    StringFormatUtil contentText = new StringFormatUtil(getContext(), AllContent, commentItem.getReply_user().getNick_name(), R.color.user_protocol).fillColor();
                    viewHolder.mTvComment.setText(contentText.getResult());
                }
            }

            //换算时间
            viewHolder.mTvTime.setText(TimeUtils.getSpaceTime(commentItem.getCreate_time()));

            //是否点赞
            if (commentItem.isLike()) {
                viewHolder.mImgLike.setImageResource(R.mipmap.icon_likett_p);
            } else {
                viewHolder.mImgLike.setImageResource(R.mipmap.icon_likett);
            }

            //设置点赞数
            viewHolder.mTvLikeCount.setText(commentItem.getLike_count() + "");

            //点赞
            viewHolder.mImgLike.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Log.e("onClick: ", "Id :" + commentItem.getId() + "  misLike" + commentItem.isLike());
                    setLike();
                }

                private void setLike() {
                    MyHttpRequest request = new MyHttpRequest(getContext());
                    String url = String.format(UrlCenter.LIKE, "comment", commentItem.getId());
                    UrlParams urlParams = new UrlParams();
                    if (!commentItem.isLike()) {
                        request.post(url, urlParams, new DataRequestListener<String>(String.class) {
                            @Override
                            public void onStart(Context context, String url) {
                                enableProgress(false);
                                super.onStart(context, url);
                            }

                            @Override
                            public void onSuccess(String o) {
                                super.onSuccess(o);
                                viewHolder.mImgLike.setImageResource(R.mipmap.icon_likett_p);
                                commentItem.setLike(true);
                                commentItem.setLike_count(commentItem.getLike_count() + 1);
                                viewHolder.mTvLikeCount.setText(commentItem.getLike_count() + "");
                            }

                            @Override
                            public void onFailure(Throwable t, int errorNo, String strMsg) {
                                super.onFailure(t, errorNo, strMsg);
                                EasyToast.showToast(getContext(), strMsg);
                            }
                        });
                    } else {
                        request.delete(url, urlParams, new DataRequestListener<String>(String.class) {
                            @Override
                            public void onStart(Context context, String url) {
                                enableProgress(false);
                                super.onStart(context, url);
                            }

                            @Override
                            public void onSuccess(String o) {
                                super.onSuccess(o);
                                viewHolder.mImgLike.setImageResource(R.mipmap.icon_likett);
                                commentItem.setLike(false);
                                commentItem.setLike_count(commentItem.getLike_count() - 1);
                                viewHolder.mTvLikeCount.setText(commentItem.getLike_count() + "");
                            }

                            @Override
                            public void onFailure(Throwable t, int errorNo, String strMsg) {
                                super.onFailure(t, errorNo, strMsg);
                                EasyToast.showToast(getContext(), strMsg);
                            }
                        });
                    }
                }
            });

            viewHolder.mCirHead.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    UserCenterActivity.start(getContext(), user.getUser_id() + "");
                }
            });

            viewHolder.mTvReply.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    CommentDialog commentDialog = CommentDialog.newInstance("评论", "写评论", 5, false);
                    commentDialog.show(getFragmentManager(), "");
                    commentDialog.setOnClickable(new CommentDialog.CommentClickable() {
                        @Override
                        public void btnEnter(String comment) {
                            MyHttpRequest request = new MyHttpRequest(getActivity());
                            String url = String.format(UrlCenter.REPLY, commentItem.getId());
                            JSONObject jobj = new JSONObject();
                            try {
                                jobj.put(ParamKey.CONTENT, comment);
                                request.post(url, jobj, new DataRequestListener<String>(String.class) {

                                    @Override
                                    public void onStart(Context context, String url) {
                                        enableProgress(false);
                                        super.onStart(context, url);
                                    }

                                    @Override
                                    public void onSuccess(String o) {
                                        super.onSuccess(o);
                                        onStartRefreshing();
                                    }

                                    @Override
                                    public void onFailure(Throwable t, int errorNo, String strMsg) {
                                        super.onFailure(t, errorNo, strMsg);
                                        EasyToast.showToast(getContext(), strMsg);
                                    }
                                });

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }
            });
        }

        public class VH extends RecyclerView.ViewHolder {

            @Bind(R.id.mImgHead)
            CircleImageView mCirHead;
            @Bind(R.id.mTvName)
            TextView mTvName;
            @Bind(R.id.mTvClubName)
            TextView mTvClubName;
            @Bind(R.id.mTvComment)
            TextView mTvComment;
            @Bind(R.id.mTvTime)
            TextView mTvTime;
            @Bind(R.id.mTvReply)
            TextView mTvReply;
            @Bind(R.id.mImgLike)
            ImageView mImgLike;
            @Bind(R.id.mTvLikeCount)
            TextView mTvLikeCount;

            public VH(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }
        }
    }
}
